package com.baymax.test.scene.demo

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.baymax.test.scene.BaseScene
import com.baymax.test.scene.MainActivity
import com.baymax.test.scene.addButton
import com.baymax.test.scene.newSceneFlexContainer

class ChainScene : BaseScene() {


    override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): View {
        return p1.newSceneFlexContainer {
            val ic = mutableListOf<Interceptor>()

            addButton("add forward") {
                ic.add(object : Interceptor() {
                    override fun intercept(chain: Chain): Response {
                        return chain.proceed()
                    }
                })
            }

            addButton("add break") {
                ic.add(object : Interceptor() {
                    override fun intercept(chain: Chain): Response {
                        return Response(chain.request, "break")
                    }
                })
            }

            addButton("clear") {
                ic.clear()
            }
            addButton("add break") {
                val r = Request(0)
                val result = Chain(r, ic).proceed()
                println("result $result" )
            }
            addButton("start") {
               val c = requireActivity()
                c.startActivity(Intent(c ,MainActivity::class.java))
                c.startActivity(Intent().apply {
                    component = ComponentName("com.baymax.sdk.address" ,"com.baymax.sdk.address.MainActivity")
                })
            }
        }
    }

    abstract class Interceptor {
        abstract fun intercept(chain: Chain): Response
    }

    data class Request(var i: Int)
    data class Response(val r: Request, var o: Any? = null)
    class Chain(val request: Request, val l: List<Interceptor>) {
        var index = 0
        fun proceed(): Response {
            return l.getOrNull(index++)?.intercept(this) ?: Response(request, "Empty")
        }
    }


}